import { defineStore } from 'pinia';
import { inject, ref } from 'vue';
import { getMineTemplate, send2Id } from 'src/api/api';
import { useUserStore } from 'stores/userStore';
import { Notify }            from 'quasar';
import { mineTemplateStore } from 'stores/mineTemplateStore';

export const useSocketStore = defineStore('socket', () => {
  const socket = ref<WebSocket>();
  const status = ref({ color: 'white', msg: '正在建立连接...' });

  console.log(socket.value?.readyState);
  const bus = inject('bus');
  const getStatus = (val: number) => {
    switch (val) {
      case 0:
        return { color: 'info', msg: '正在建立连接...' };
      case 1:
        return { color: 'green', msg: '在线' };
      case 2:
        return { color: 'red', msg: '正在关闭连接...' };
      case 3:
        return { color: 'yellow', msg: '重连中...' };
      default:
        return { color: 'grey', msg: '服务器断开' };
    }
  };
  const initSocket = (id: number): void => {
    setInterval(() => {
      if (socket.value?.readyState !== 1) {
        socket.value = undefined;
        console.log('重连中...:' + socket.value?.readyState);
        socket.value = new WebSocket(
          'wss://localhost:8080/portal/open/websocket/' + id + '/win'
          // 'ws://139.159.184.159:8080/portal/open/websocket/1/app'
        );
        socket.value.onopen = () => {
          console.log('连接成功');
          useUserStore().getUserOnline();
          status.value = getStatus(<number>socket.value?.readyState);
          console.log('id', id);
          send2Id({
            id: [...(id + '')],
            msg: JSON.stringify({
              code: 1,
              content: 'win',
            }),
          });
        };
        socket.value.onclose = () => {
          console.log('连接关闭');
        };
        socket.value.onmessage = async (event) => {
          const message = event.data;
          console.log('收到消息：' + message);
          const res = JSON.parse(message) as { code: number; content: string };
          bus.emit('socketMsg', message);
          console.log(JSON.parse(message));
          if (res.content != 'win') {
            switch (res.code) {
              case 1:
                Notify.create({
                  message: res.content + '上线了',
                  color: 'green',
                  timeout: 2000,
                });
                await useUserStore().getUserOnline();
                break;
              case 2:
                Notify.create({
                  message: res.content + '模板有更新',
                  color: 'green',
                  timeout: 2000,
                });
                mineTemplateStore().getMineTemplateStore();
                break;
              case 3:
                Notify.create({
                  message: res.content + '数据库配置有更新',
                  color: 'green',
                  timeout: 2000,
                });
                break;
              default:
                break;
            }
          }
        };
      }
    }, 1200);
  };
  return {
    initSocket,
    socket,
    status,
  };
});
